package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    private final StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    private final CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
//        cacheClient.queryWithLogicalExpire(RedisConstants.CACHE_SHOP_KEY);
        //测试缓存穿透问题解决得怎么样
//        Shop shop = cacheClient.queryWithPassThrough(
//                RedisConstants.CACHE_SHOP_KEY,
//                id, Shop.class,
//                this::getById,
//                Duration.ofMinutes(RedisConstants.CACHE_NULL_TTL),
//                Duration.ofMinutes(RedisConstants.CACHE_SHOP_TTL)
//        );
        Shop shop = queryWithMutex(id);
        if (shop == null) {
            return Result.fail("查询的商品不存在");
        } else {
            return Result.ok(shop);
        }
//        return null;
    }


    public Shop queryWithMutex(Long id) {
        //存入redis的shopKey
        String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
        //有关shop互斥锁的key
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = false;
        Shop shop = null;
        try {
            while(!isLock) {
                //尝试从缓存中获取shop
                String shopJson = stringRedisTemplate.opsForValue().get(shopKey);

                //可以从缓存里面取到数据
                if (StrUtil.isNotBlank(shopJson)) {
                    shop = JSONUtil.toBean(shopJson, Shop.class);
                    log.info("缓存返回商品：shop：{}， shopJson：{}", shop, shopJson);
                    return shop;
                }

                //缓存拿到的值若是空字符串，代表不存在
                if(shopJson != null) {
                    return null;
                }

                //只有换出那种真的不存在的时候，才会去获取互斥锁
                isLock = tryLock(lockKey);

                //如果拿到了互斥锁就去查数据库，然后改缓存
                if (isLock) {
                    log.info("拿到锁了");

                    shopJson = stringRedisTemplate.opsForValue().get(shopKey);
                    //可以从缓存里面取到数据
                    if (StrUtil.isNotBlank(shopJson)) {
                        shop = JSONUtil.toBean(shopJson, Shop.class);
//                        log.info("走的缓存");
//                    log.info("缓存返回商品：shop：{}， shopJson：{}", shop, shopJson);
                        return shop;
                    }

                    //缓存拿到的值若是空字符串，代表不存在
                    if(shopJson != null) {
                        return null;
                    }

                    //去数据库拿数据
                    shop = getById(id);
                    //模拟复杂构建的延迟
                    Thread.sleep(200);
                    //数据库都没得只能返回店铺不存在了
                    if (shop == null) {
                        log.error("数据库没有查询到该商品：{}", id);
                        //把""写入redis，防止缓存穿透
                        stringRedisTemplate.opsForValue().set(shopKey, "", Duration.ofMinutes(RedisConstants.CACHE_NULL_TTL));
                        return null;
                    }
                    //因为redis里面没得，所以要存进去，存进去后就可以把数据传给前端了
                    stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop), Duration.ofMinutes(RedisConstants.CACHE_SHOP_TTL));
//                    log.info("缓存中没有，从数据库中取来：{}", shop);
                    unlock(lockKey);
                    break;
                } else {
//                    log.error("没有拿到锁");
                    //拿不到锁就休眠后再尝试，互斥锁防止缓存击穿
                    Thread.sleep(50);
                }
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return shop;
    }


    public Shop queryWithPassThrough(Long id) {
        //存入redis的shopKey
        String shopKey = RedisConstants.CACHE_SHOP_KEY + id;

        //从redis中获取shop
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);
        Shop shop = null;

        //判断shopJSON是否为空，不为空直接就返回了
        if (StrUtil.isNotBlank(shopJson)) {
            shop = JSONUtil.toBean(shopJson, Shop.class);
            log.info("缓存返回商品：shop：{}， shopJson：{}", shop, shopJson);
            return shop;
        }
        //判断命中的是否是空值
        if(shopJson == null) {
//            return Result.fail("店铺信息不存在！");
            return null;
        }

        //去数据库拿数据
        shop = getById(id);
        //数据库都没得只能返回店铺不存在了
        if (shop == null) {
            log.error("数据库没有查询到该商品：{}", id);
            stringRedisTemplate.opsForValue().set(shopKey, "", Duration.ofMinutes(RedisConstants.CACHE_NULL_TTL));
//            return Result.fail("店铺不存在");
            return null;
        }
        //因为redis里面没得，所以要存进去，存进去后就可以把数据传给前端了
        stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop), Duration.ofMinutes(RedisConstants.CACHE_SHOP_TTL));
        log.info("缓存中没有，从数据库中取来：{}", shop);
//        return Result.ok(shop);
        return shop;
    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不为空");
        }
        updateById(shop);
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    private boolean tryLock(String key) {
        return BooleanUtil.isTrue(stringRedisTemplate.opsForValue().setIfAbsent(key, "1", Duration.ofSeconds(RedisConstants.LOCK_SHOP_TTL)));
    }

    /**
     * 释放锁
     * @param key 锁的key
     */
    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }
}
